package com.example.zhilongzhang.constructionpayapp.http;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.example.zhilongzhang.constructionpayapp.activity.LoginActivity;
import com.example.zhilongzhang.constructionpayapp.base.App;
import com.example.zhilongzhang.constructionpayapp.util.SpUtil;
import com.google.gson.Gson;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.OkHttpRequestBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Credentials;

/**
 * Created by Administrator on 2017/11/17.
 */

public class HttpBase {
    public static final String Url = "";
    private static String BaseUrl = "";

    public static void GetInterfaceData(String urlFile, String interfaceName, StringCallback callback){
        GetInterfaceData(urlFile, interfaceName, callback, true);
    }
    public static void GetInterfaceDataTag(Context activity, String urlFile, String interfaceName, StringCallback callback){
        GetInterfaceDataTag(activity,urlFile, interfaceName, callback, true);
    }

    public static void GetInterfaceData(String urlFile, String interfaceName, StringCallback callback, boolean hasToken ){
        GetInterfaceData(urlFile, interfaceName, null, callback, hasToken);
    }

    public static void GetInterfaceData(String urlFile, String interfaceName, StringCallback callback,String httptype, boolean hasToken ){
        GetInterfaceData(urlFile, interfaceName, null, callback,httptype, hasToken);
    }
    public static void GetInterfaceDataTag(Context activity, String urlFile, String interfaceName, StringCallback callback, boolean hasToken ){
        GetInterfaceDataTag(activity,urlFile, interfaceName, null, callback, hasToken);
    }

    //基础参数重写，默认添加token和get
    public static void GetInterfaceData(String urlFile, String interfaceName, Map<String,String> params, StringCallback callback){
        GetInterfaceData(urlFile, interfaceName, params, callback, true);
    }
    //基础参数重写，默认添加token和get
    public static void GetInterfaceDataTag(Context activity, String urlFile, String interfaceName, Map<String,String> params, StringCallback callback){
        GetInterfaceDataTag(activity,urlFile, interfaceName, params, callback, true);
    }

    //基础参数重写，默认添加get
    public static void GetInterfaceData(String urlFile, String interfaceName, Map<String,String> params, StringCallback callback, boolean hasToken){
        GetInterfaceData(urlFile, interfaceName, params, callback, "get", hasToken);
    }

    //基础参数重写，默认添加get
    public static void GetInterfaceDataTag(Context activity, String urlFile, String interfaceName, Map<String,String> params, StringCallback callback, boolean hasToken){
        GetInterfaceDataTag(activity,urlFile, interfaceName, params, callback, "get", hasToken);
    }

    //基础参数重写，默认添加token
    public static void GetInterfaceData(String urlFile, String interfaceName, Map<String,String> params, StringCallback callback, String httptype){
        GetInterfaceData(urlFile, interfaceName, params, callback, httptype, true);
    }

    //基础参数重写，默认添加token
    public static void GetInterfaceDataTag(Context activity, String urlFile, String interfaceName, Map<String,String> params, StringCallback callback, String httptype){
        GetInterfaceDataTag(activity,urlFile, interfaceName, params, callback, httptype, true);
    }

    //接口调用基础函数
    public static void GetInterfaceData(String urlFile, final String interfaceName, Map<String,String> params, final StringCallback callback, String httptype, final boolean hasToken){
        OkHttpRequestBuilder postItem = OkHttpUtils.get();
        switch (httptype){
            case "post":{ postItem = OkHttpUtils.post(); break; }
        }
        postItem = ParamsHandle(postItem, urlFile, interfaceName, params, hasToken);
        postItem.build().execute(ReturnDataHandle(interfaceName, callback, hasToken));
    }
    //接口调用基础函数待Tag
    public static void GetInterfaceDataTag(Context activity, String urlFile, final String interfaceName, Map<String,String> params, final StringCallback callback, String httptype, final boolean hasToken){
        OkHttpRequestBuilder postItem = OkHttpUtils.get();
        switch (httptype){
            case "post":{ postItem = OkHttpUtils.post(); break; }
        }
        postItem = ParamsHandle(postItem, urlFile, interfaceName, params, hasToken);
        postItem.build().execute(ReturnDataHandle(interfaceName, callback, hasToken));
    }

    public static void UpdateFileData(String urlFile, final String interfaceName, ArrayList<String> filepaths, final StringCallback callback){
        UpdateFileData(urlFile, interfaceName, filepaths, callback, true);
    }

    public static void UpdateFileData(String urlFile, final String interfaceName, ArrayList<String> filepaths, final StringCallback callback, final boolean hasToken) {
        UpdateFileData(urlFile, interfaceName, null, filepaths, callback, hasToken);
    }

    public static void UpdateFileData(String urlFile, final String interfaceName, Map<String,String> params, ArrayList<String> filepaths, final StringCallback callback){
        UpdateFileData(urlFile, interfaceName, params, filepaths, callback, true);
    }

    //上传文件基础函数
    public static void UpdateFileData(String urlFile, final String interfaceName, Map<String,String> params, ArrayList<String> filepaths, final StringCallback callback, final boolean hasToken){
        PostFormBuilder postItem = (PostFormBuilder)ParamsHandle(OkHttpUtils.post(), urlFile, interfaceName, params, hasToken);
        for (int i = 0; i < filepaths.size(); i++) {
            String filename = filepaths.get(i);
            try{
                if(filename.length() > 2) {
                    File file = new File(filename);
                    postItem.addFile("mFile", file.getName(), file);
                    //Log.e("调用接口" + interfaceName, "文件" + filename);
                }
            }
            catch (Exception ex){
                //Log.e("调用接口出错" + interfaceName, ex.getMessage());
            }
            finally {

            }
        }
        postItem.build().writeTimeOut(20000).execute(ReturnDataHandle(interfaceName, callback, hasToken));
    }

    //接口参数处理函数
    private static OkHttpRequestBuilder ParamsHandle(final OkHttpRequestBuilder postItem, String urlFile, final String interfaceName, Map<String,String> params, final boolean hasToken){
        String baseweb = BaseUrl + urlFile;
        //接口名称
        //postItem.url(baseweb).addParams("",interfaceName);
        //String request = baseweb + "?interfaceName=" + interfaceName;
        postItem.url(baseweb);
        String request = baseweb + "?";
        if(params != null) {
            boolean isFrist=true;
            for (String key : params.keySet()) {
                String value = params.get(key);
                if(TextUtils.isEmpty(value)){ value = ""; }
                postItem.addParams(key, value);
                if (isFrist){
                    isFrist=false;
                    request += (key + "=" + params.get(key));
                }else {
                    request += ("&" + key + "=" + params.get(key));
                }

            }
        }
        if(hasToken){
            //Todo--设置Toke
            postItem.addParams("os", "android");
            request += ("&os=" + "android");
        }
        Log.e("调用接口(拼接)" + interfaceName, request);
        return postItem;
    }


    //接口调用回调处理
    private static StringCallback ReturnDataHandle(final String interfaceName, final StringCallback callback, final boolean hasToken){
        return new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                if (request!=null){
                    if (e!=null){
                        try {
                            Log.e("调用接口出错" + interfaceName, e.getMessage());
                        }catch (Exception e1){
                            Log.e("调用接口出错" + interfaceName, "mssage空的");
                        }

                    }

                }
                callback.onError(request, e);
            }
            @Override
            public void onResponse(String response) {
                Log.e("调用接口(返回)" + interfaceName, response);
                if (response!=null && !response.equals("")){
                    Bean data = new Gson().fromJson(response, Bean.class);
                    if (data.code==1001){
                        SpUtil.setTel("");
                        SpUtil.setShopName("");
                        SpUtil.setShopId("");
                        SpUtil.setToken("");
                        SpUtil.setUserName("");
                        SpUtil.setPassword("");
                        Intent intent = new Intent();
                        intent.setClass(App.mContext, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                        App.mContext.startActivity(intent);
                    }else {
                        callback.onResponse(response);
                    }
                }
            }
        };
    }
    //PostString
    public static void GetInterfaceStr(String urlFile, String interfaceName, Map<String,Object> params, StringCallback callback){
        GetInterfaceStr(urlFile, interfaceName, params, callback, true);
    }
    //PostString
    public static void GetInterfaceStr(String urlFile, final String interfaceName, Map<String,Object> params, final StringCallback callback,final boolean hasToken){
        Log.e("requesPass","json="+new Gson().toJson(params));
        Log.e("requesPass","urlFile="+urlFile+"?os=android&access_token="+SpUtil.getToken()+"&username="+SpUtil.getUserName());
        OkHttpUtils.postString()
                .url(urlFile+"?os=android&access_token="+SpUtil.getToken()+"&username="+SpUtil.getUserName())
                .content(new Gson().toJson(params))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(ReturnDataHandle(interfaceName, callback, hasToken));

    }
}
